package connect

import (
	"encoding/json"
	"fmt"
	"ghw2/namesrv/Mapper"
	"net"
)

type response struct {
	Services []string `json:"services"`
	Msg      string   `json:"msg"`
}

func ClientConnProcess(conn *net.Conn) {
	defer func() {
		(*conn).Close()
		if err := recover(); err != nil {
			fmt.Println("客户端连接崩溃:" + (*conn).RemoteAddr().String())
			fmt.Println(err)
			fmt.Println()
		}
	}()

	//这里我们采取客户端主动拉取策略，即客户端应该在较为合适的时间段内请求路由服务信息
	buffer := make([]byte, 1023)
	var n int
	var err error
	var service string
	for {
		n, err = (*conn).Read(buffer)
		if err != nil {
			panic(err)
		}
		service = string(buffer[:n])
		fmt.Println("Receiver client request for service ", service)
		for k, v := range Mapper.ServiceAddressMapper {
			fmt.Println(k, v)
		}
		var res response
		if v, ok := Mapper.ServiceAddressMapper[service]; ok {
			res.Msg = "ok"
			res.Services = v.Addresses
		} else {
			res.Msg = "fail"
		}
		data, _ := json.Marshal(res)
		fmt.Printf("**********\nSend route data:%v\n", res)
		(*conn).Write(data)
	}
}
